package com.woniuxy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.conmon.MyPageData;
import com.woniuxy.mapper.*;
import com.woniuxy.pojo.*;
import com.woniuxy.pojo.dto.AppointmentRecordDTO;
import com.woniuxy.pojo.dto.SearchAppointmentRecordDTO;
import com.woniuxy.pojo.vo.AppointmentRecordVO;
import com.woniuxy.service.AppointmentRecordService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
* @author admin
* @description 针对表【appointment_record(预约记录表)】的数据库操作Service实现
* @createDate 2025-06-09 20:19:56
*/
@Service
public class AppointmentRecordServiceImpl extends ServiceImpl<AppointmentRecordMapper, AppointmentRecord>
    implements AppointmentRecordService {
    @Autowired
    private AppointmentRecordMapper appointmentRecordMapper;
    @Autowired
    private DoctorScheduleMapper doctorScheduleMapper;
    @Autowired
    private HospitalMapper hospitalMapper;
    @Autowired
    private MedicalPackageMapper medicalPackageMapper;
    @Autowired
    private DepartmentMapper departmentMapper;
    @Autowired
    private DoctorMapper  doctorMapper;


    @Override
    public MyPageData getAppointmentRecord(Integer pageNum, Integer pageSize) {
        Page<AppointmentRecord> page = new Page<>(pageNum, pageSize);
        QueryWrapper<AppointmentRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id", "schedule_id", "patient_name", "phone", "order_no", "appointment_time");
        Page<AppointmentRecord> appointmentRecordPage = appointmentRecordMapper.selectPage(page, queryWrapper);
        List<AppointmentRecord> records = appointmentRecordPage.getRecords();
        MyPageData myPageData = new MyPageData(appointmentRecordPage.getTotal(), records);
        return myPageData;

    }

    @Override
    public AppointmentRecordVO getAppointmentDetail(Integer id) {
        // 1. 获取排班记录
        DoctorSchedule schedule = doctorScheduleMapper.selectById(id);
        if (schedule == null) {
            throw new RuntimeException("未找到ID为" + id + "的排班记录");
        }

        // 2. 获取医院信息
        Hospital hospital = hospitalMapper.selectById(schedule.getHospitalId());
        //3. 获取套餐信息
        MedicalPackage medicalPackage = medicalPackageMapper.selectById(schedule.getPackageId());
        // 3. 构建返回对象
        AppointmentRecordVO vo = new AppointmentRecordVO();
        vo.setHospitalName(hospital != null ? hospital.getName() : "未知医院");
        vo.setId(schedule.getId());
        vo.setRegisteredCount(schedule.getRegisteredCount());
        vo.setPackageName(medicalPackage.getPackageName());
        return vo;
    }

    @Override
    public MyPageData getFetchData(Integer pageNum, Integer pageSize) {
        // 1. 直接查询预约记录表
        Page<AppointmentRecord> page = new Page<>(pageNum, pageSize);
        Page<AppointmentRecord> recordPage = appointmentRecordMapper.selectPage(page, null);

        // 2. 处理查询结果
        List<AppointmentRecordDTO> dtoList = recordPage.getRecords().stream().map(record -> {
            AppointmentRecordDTO dto = new AppointmentRecordDTO();
            BeanUtils.copyProperties(record, dto);

            // 从预约记录中获取相关ID
            Integer scheduleId = record.getScheduleId();

            // 获取排班信息
            DoctorSchedule schedule = doctorScheduleMapper.selectById(scheduleId);
            if (schedule != null) {
                // 设置费用
                dto.setFee(schedule.getFee());

                // 设置时间段（上午/下午）
                dto.setTimePeriod(schedule.getTimePeriod());
                dto.setStartTime(schedule.getStartTime());
                // 设置排班日期（即就诊日期）
                dto.setScheduleDate(schedule.getScheduleDate());

                // 处理医院名称
                if (schedule.getHospitalId() != null) {
                    Hospital hospital = hospitalMapper.selectById(schedule.getHospitalId());
                    if (hospital != null) {
                        dto.setHospitalName(hospital.getName());
                    }
                }

                // 处理科室名称（格式：一级科室>二级科室）
                if (schedule.getDepartmentId() != null) {
                    Department department = departmentMapper.selectById(schedule.getDepartmentId());
                    if (department != null) {
                        if (department.getParentId() != null) {
                            Department parentDept = departmentMapper.selectById(department.getParentId());
                            if (parentDept != null) {
                                dto.setDepartmentName(parentDept.getName() + ">" + department.getName());
                            } else {
                                dto.setDepartmentName(department.getName());
                            }
                        } else {
                            dto.setDepartmentName(department.getName());
                        }
                    }
                }
            }

            // 设置下单时间 = 预约时间
            dto.setAppointmentTime(record.getAppointmentTime());

            // 设置状态显示文本
            if (dto.getStatus() != null) {
                switch (dto.getStatus().toLowerCase()) {
                    case "unpaid": dto.setStatus("未支付"); break;
                    case "paid": dto.setStatus("已支付"); break;
                    case "canceled": dto.setStatus("已取消"); break;
                    case "completed": dto.setStatus("已完成"); break;
                    default: // 保持原样
                }
            }

            return dto;
        }).collect(Collectors.toList());

        // 3. 返回分页结果
        return new MyPageData(recordPage.getTotal(), dtoList);
    }

    @Override
    public List<String> getStatuss() {
        QueryWrapper<AppointmentRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("DISTINCT status");
        List<AppointmentRecord> appointmentRecords = appointmentRecordMapper.selectList(queryWrapper);
        return appointmentRecords.stream()
                .map(AppointmentRecord::getStatus)
                .collect(Collectors.toList());
    }

    @Override
    public MyPageData searchAppointmentRecord(Integer pageNum, Integer pageSize, SearchAppointmentRecordDTO queryDTO) {
        // 1. 创建分页对象
        Page<AppointmentRecord> page = new Page<>(pageNum, pageSize);

        // 2. 构建查询条件
        QueryWrapper<AppointmentRecord> queryWrapper = new QueryWrapper<>();

        // 3. 添加基本查询条件
        if (StringUtils.isNotBlank(queryDTO.getOrderNo())) {
            queryWrapper.like("order_no", queryDTO.getOrderNo());
        }
        if (StringUtils.isNotBlank(queryDTO.getStatus())) {
            queryWrapper.eq("status", queryDTO.getStatus());
        }
        if (StringUtils.isNotBlank(queryDTO.getPatientName())) {
            queryWrapper.like("patient_name", queryDTO.getPatientName());
        }

        // 4. 处理科室名称条件
        if (StringUtils.isNotBlank(queryDTO.getDepartmentName())) {
            // 使用IN查询简化SQL
            List<Integer> deptIds = departmentMapper.findIdsByName(queryDTO.getDepartmentName());

            if (deptIds != null && !deptIds.isEmpty()) {
                // 通过科室ID查询关联的排班ID
                List<Integer> scheduleIds = doctorScheduleMapper.findIdsByDepartmentIds(deptIds);

                if (scheduleIds != null && !scheduleIds.isEmpty()) {
                    queryWrapper.in("schedule_id", scheduleIds);
                } else {
                    queryWrapper.apply("1 = 2"); // 强制返回空结果
                }
            } else {
                queryWrapper.apply("1 = 2"); // 强制返回空结果
            }
        }

        // 5. 执行分页查询
        Page<AppointmentRecord> recordPage = appointmentRecordMapper.selectPage(page, queryWrapper);

        // 6. 处理结果
        return processRecords(recordPage);
    }

    private MyPageData processRecords(Page<AppointmentRecord> recordPage) {
        List<AppointmentRecord> records = recordPage.getRecords();

        // 7. 转换为DTO并补充科室信息
        List<SearchAppointmentRecordDTO> dtoList = records.stream().map(record -> {
            SearchAppointmentRecordDTO dto = new SearchAppointmentRecordDTO();
            BeanUtils.copyProperties(record, dto);

            // 获取排班信息以确定科室
            DoctorSchedule schedule = doctorScheduleMapper.selectById(record.getScheduleId());
            if (schedule != null && schedule.getDepartmentId() != null) {
                Department department = departmentMapper.selectById(schedule.getDepartmentId());
                if (department != null) {
                    if (department.getParentId() != null) {
                        Department parentDept = departmentMapper.selectById(department.getParentId());
                        if (parentDept != null) {
                            dto.setDepartmentName(parentDept.getName() + ">" + department.getName());
                        } else {
                            dto.setDepartmentName(department.getName());
                        }
                    } else {
                        dto.setDepartmentName(department.getName());
                    }
                }
            }
            return dto;
        }).collect(Collectors.toList());

        // 8. 返回包含分页信息的对象
        return new MyPageData(recordPage.getTotal(), dtoList);
    }

    @Override
    public MyPageData searchAppointment(Integer pageNum, Integer pageSize, SearchAppointmentRecordDTO queryDTO) {
        // 1. 创建分页对象
        Page<AppointmentRecord> page = new Page<>(pageNum, pageSize);

        // 2. 构建查询条件
        QueryWrapper<AppointmentRecord> queryWrapper = new QueryWrapper<>();

        // 3. 添加基本查询条件
        if (StringUtils.isNotBlank(queryDTO.getOrderNo())) {
            queryWrapper.like("order_no", queryDTO.getOrderNo());
        }

        if (StringUtils.isNotBlank(queryDTO.getPatientName())) {
            queryWrapper.like("patient_name", queryDTO.getPatientName());
        }

        if (StringUtils.isNotBlank(queryDTO.getPhone())) {
            queryWrapper.like("phone", queryDTO.getPhone());
        }

        if (StringUtils.isNotBlank(queryDTO.getStatus())) {
            queryWrapper.eq("status", queryDTO.getStatus());
        }

        // 4. 处理医院名称条件
        if (StringUtils.isNotBlank(queryDTO.getHospitalName())) {
            // 查询医院ID列表
            QueryWrapper<Hospital> hospitalQuery = new QueryWrapper<>();
            hospitalQuery.select("id").like("name", queryDTO.getHospitalName());
            List<Long> hospitalIds = hospitalMapper.selectObjs(hospitalQuery).stream()
                    .map(id -> (Long) id)
                    .collect(Collectors.toList());

            if (!hospitalIds.isEmpty()) {
                // 查询关联的排班ID
                QueryWrapper<DoctorSchedule> scheduleQuery = new QueryWrapper<>();
                scheduleQuery.select("id").in("hospital_id", hospitalIds);
                List<Long> scheduleIds = doctorScheduleMapper.selectObjs(scheduleQuery).stream()
                        .map(id -> (Long) id)
                        .collect(Collectors.toList());

                if (!scheduleIds.isEmpty()) {
                    queryWrapper.in("schedule_id", scheduleIds);
                } else {
                    queryWrapper.apply("1 = 2"); // 强制返回空结果
                }
            } else {
                queryWrapper.apply("1 = 2"); // 强制返回空结果
            }
        }

        // 5. 处理科室条件 (使用现有字段 departmentName 表示一级科室)
        if (StringUtils.isNotBlank(queryDTO.getDepartmentName())) {
            // 查询一级科室ID（父级为null的科室）
            QueryWrapper<Department> deptQuery = new QueryWrapper<>();
            deptQuery.select("id").isNull("parent_id").eq("name", queryDTO.getDepartmentName());
            List<Integer> firstLevelDeptIds = departmentMapper.selectObjs(deptQuery).stream()
                    .map(id -> (Integer) id)
                    .collect(Collectors.toList());

            if (!firstLevelDeptIds.isEmpty()) {
                // 查询该一级科室下的所有二级科室ID
                QueryWrapper<Department> subDeptQuery = new QueryWrapper<>();
                subDeptQuery.select("id").in("parent_id", firstLevelDeptIds);
                List<Integer> subDeptIds = departmentMapper.selectObjs(subDeptQuery).stream()
                        .map(id -> (Integer) id)
                        .collect(Collectors.toList());

                // 合并一级和二级科室ID
                List<Integer> allDeptIds = new ArrayList<>();
                allDeptIds.addAll(firstLevelDeptIds);
                allDeptIds.addAll(subDeptIds);

                if (!allDeptIds.isEmpty()) {
                    // 查询关联这些科室的排班ID
                    QueryWrapper<DoctorSchedule> scheduleQuery = new QueryWrapper<>();
                    scheduleQuery.select("id").in("department_id", allDeptIds);
                    List<Integer> scheduleIds = doctorScheduleMapper.selectObjs(scheduleQuery).stream()
                            .map(id -> (Integer) id)
                            .collect(Collectors.toList());

                    if (!scheduleIds.isEmpty()) {
                        queryWrapper.in("schedule_id", scheduleIds);
                    } else {
                        queryWrapper.apply("1 = 2"); // 强制返回空结果
                    }
                } else {
                    queryWrapper.apply("1 = 2"); // 强制返回空结果
                }
            } else {
                queryWrapper.apply("1 = 2"); // 强制返回空结果
            }
        }

        // 6. 执行分页查询
        Page<AppointmentRecord> recordPage = appointmentRecordMapper.selectPage(page, queryWrapper);

        // 7. 处理结果并转换DTO
        List<AppointmentRecord> records = recordPage.getRecords();

        List<AppointmentRecordDTO> dtoList = records.stream().map(record -> {
            AppointmentRecordDTO dto = new AppointmentRecordDTO();
            BeanUtils.copyProperties(record, dto);

            // 获取排班信息
            DoctorSchedule schedule = doctorScheduleMapper.selectById(record.getScheduleId());
            if (schedule != null) {
                dto.setFee(schedule.getFee());
                dto.setTimePeriod(schedule.getTimePeriod().toString());
                dto.setStartTime(schedule.getStartTime());
                dto.setScheduleDate(schedule.getScheduleDate());

                // 处理医院名称
                if (schedule.getHospitalId() != null) {
                    Hospital hospital = hospitalMapper.selectById(schedule.getHospitalId());
                    if (hospital != null) {
                        dto.setHospitalName(hospital.getName());
                    }
                }

                // 处理科室信息（一级科室>二级科室）
                if (schedule.getDepartmentId() != null) {
                    Department department = departmentMapper.selectById(schedule.getDepartmentId());
                    if (department != null) {
                        if (department.getParentId() != null) {
                            Department parentDept = departmentMapper.selectById(department.getParentId());
                            if (parentDept != null) {
                                dto.setDepartmentName(parentDept.getName() + ">" + department.getName());
                            } else {
                                dto.setDepartmentName(department.getName());
                            }
                        } else {
                            dto.setDepartmentName(department.getName());
                        }
                    }
                }
            }

            // 设置状态显示文本
            if (dto.getStatus() != null) {
                switch (dto.getStatus().toLowerCase()) {
                    case "unpaid": dto.setStatus("未支付"); break;
                    case "paid": dto.setStatus("已支付"); break;
                    case "canceled": dto.setStatus("已取消"); break;
                    case "completed": dto.setStatus("已完成"); break;
                }
            }

            return dto;
        }).collect(Collectors.toList());

        // 8. 返回分页结果
        return new MyPageData(recordPage.getTotal(), dtoList);
    }


    @Override
    public AppointmentRecordDTO getOrderDetail(Integer id) {
        // 1. 查询订单基本信息
        DoctorSchedule record = doctorScheduleMapper.selectById(id);
        AppointmentRecord order = appointmentRecordMapper.selectById(id);

        // 2. 查询关联的医院信息
        Hospital hospital = hospitalMapper.selectById(record.getHospitalId());

        // 3. 查询关联的医生信息
        Doctor doctor = doctorMapper.selectById(record.getDoctorId());


        // 5. 查询关联的科室信息
        Department department = departmentMapper.selectById(doctor.getDepartmentId());

        // 6. 构建并返回VO对象
        AppointmentRecordDTO vo = new AppointmentRecordDTO();
        vo.setId(id);
        vo.setOrderNo(order.getOrderNo());
        vo.setAppointmentTime(order.getAppointmentTime());
        vo.setPatientName(order.getPatientName());
        vo.setPhone(order.getPhone());

        vo.setFee(record.getFee());
        vo.setStatus((String) record.getStatus());
        vo.setStartTime(record.getStartTime());
        vo.setScheduleDate(record.getScheduleDate());
        vo.setTimePeriod(record.getTimePeriod());

        vo.setHospitalName(hospital.getName());
        vo.setAddress(hospital.getAddress());

        vo.setDoctorName(doctor.getName());
        vo.setTitle(doctor.getTitle());

        vo.setDepartmentName(department.getName());



        return vo;
    }
}




